<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑导航End -->

    <el-card>
      <el-row>
        <el-col
          ><el-button
            type="primary"
            style="margin-bottom: 15px"
            @click="addCateOperation"
            >添加分类</el-button
          ></el-col
        >
      </el-row>

      <!-- 商品分类表格 -->
      <!-- 
        data - 绑定数据源
        columns - 定义竖行的内容，它是一个数组，数组中的每个对象就代表一个竖行所要展示的内容
        selection-type - 是否为多选类型的表格，默认值是true
        expand-type - 展开行效果
        show-index - 显示数据的索引值
        index-text - 自定义索引名称，默认的是‘序号’两个字
        border - 表格竖行分割线
       -->
      <tree-table
        :data="categoriesData"
        :columns="columns"
        show-header
        children-prop="children"
        border
        stripe
        :expand-type="false"
        :selection-type="false"
        show-index
        index-text="#"
      >
        <!-- 是否有效 -->
        <template slot="isValidate" slot-scope="scope">
          <i
            class="el-icon-success"
            style="color: #67c23a"
            v-if="!scope.row.cat_deleted"
          ></i>
          <i class="el-icon-error" style="color: #f56c6c" v-else></i>
        </template>
        <!-- 排序 -->
        <template slot="inSort" slot-scope="scope">
          <el-tag type="primary" size="mini" hit v-if="scope.row.cat_level == 0"
            >一级</el-tag
          >
          <el-tag
            type="success"
            size="mini"
            hit
            v-else-if="scope.row.cat_level == 1"
            >二级</el-tag
          >
          <el-tag type="warning" size="mini" hit v-else>三级</el-tag>
        </template>
        <!-- 操作按钮 -->
        <template slot="opearCate" slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="editCateInfo(scope.row)"
          >
            <i class="el-icon-edit"></i>编辑
          </el-button>
          <el-button type="danger" size="mini" @click="deleteCate(scope.row)">
            <i class="el-icon-delete"></i>删除
          </el-button>
        </template>
      </tree-table>
      <!-- 商品分类表格End -->

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="curPage"
        :page-sizes="[3, 5, 7, 9]"
        :page-size="cateParams.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="catesTotal"
        class="mt-15"
      >
      </el-pagination>
      <!-- 分页End -->

      <!-- 添加分类对话框 -->
      <el-dialog
        title="添加分类"
        :visible.sync="addCateDialogVisible"
        width="50%"
        @close="addCateDialogClosed"
      >
        <el-form ref="addCateForm" :model="addCateFormData" label-width="80px">
          <el-form-item
            label="分类名称"
            prop="cat_name"
            :rules="addCateRules.cat_name"
          >
            <el-input v-model="addCateFormData.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类">
            <el-cascader
              expand-trigger="hover"
              :options="categoriesTo2LevelData"
              :props="addCateConfig"
              v-model="selectedKeys"
              @change="parentCateChanged"
              class="cascader-select"
              separator="/"
              change-on-select
              clearable
              :show-all-levels="true"
            >
            </el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addCateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveAddCate">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加分类对话框End -->

      <!-- 编辑分类对话框 -->
      <el-dialog title="编辑分类" :visible.sync="editDialogVisible" width="50%">
        <el-form
          ref="editInfoForm"
          :model="editCateInfoForm"
          label-width="80px"
        >
          <el-form-item
            label="分类名称"
            :rules="{
              required: true,
              message: '请输入分类名称',
              trigger: ['change', 'blur'],
            }"
          >
            <el-input v-model="editCateInfoForm.cate_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="savaEditCateInfo">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑分类对话框End -->
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      categoriesData: [],
      categoriesTo2LevelData: [],
      cateParams: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },

      // 表格各列的配置
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          // 列的标题名称
          label: "是否有效",
          // 将当前列定义为模板列
          type: "template",
          // 表示当前这一列使用模块名称
          template: "isValidate",
        },
        {
          label: "排序",
          type: "template",
          template: "inSort",
        },
        {
          label: "操作",
          type: "template",
          template: "opearCate",
        },
      ],

      curPage: 1,
      catesTotal: 0,

      // 添加分类对话框
      addCateDialogVisible: false,
      editDialogVisible: false,

      // 当前编辑的对象
      curEditId: 0,

      // 添加分类对话框数据绑定
      addCateFormData: {
        // 分类名称
        cat_name: "",
        // 分类的等级,默认添加的是1级分类
        cat_level: 0,
        // 父分类
        cat_pid: 0,
      },
      // 编辑分类表单数据绑定
      editCateInfoForm: {
        cate_name: "",
      },

      // 添加分类父级选择
      selectedKeys: [],

      // 添加分类规则
      addCateRules: {
        cat_name: [
          {
            required: true,
            message: "请输入分类名称",
            trigger: ["blur", "change"],
          },
        ],
      },

      // 添加分类的配置选项
      addCateConfig: {
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
    };
  },

  created() {
    // 获取商品种类
    this.getCategory();
  },

  methods: {
    async getCategory() {
      let { data: res } = await this.$http("/categories", {
        params: this.cateParams,
      });

      if (res.meta.status !== 200) return this.$message.error("获取分类失败");
      this.$message.success("获取分类成功");
      console.log(res);
      this.categoriesData = res.data.result;
      this.catesTotal = res.data.total;
    },

    // 每页显示条数
    handleSizeChange(val) {
      this.cateParams.pagesize = val;
      this.getCategory();
      // console.log(val);
    },
    // 当前页
    handleCurrentChange(val) {
      console.log(val);
      this.cateParams.pagenum = val;
      this.getCategory();
    },

    // 添加分类中的选择项发生变化时触发
    parentCateChanged(val) {
      if (this.selectedKeys.length > 0) {
        // 如果selectedKeys数组中的length大于0,就证明选中了父级分类
        // 反之,就说明没有选中任何父级分类
        // 当前分类的等级赋值
        this.addCateFormData.cat_level = this.selectedKeys.length;
        // 父级分类的id
        this.addCateFormData.cat_pid = this.selectedKeys[
          this.selectedKeys.length - 1
        ];
      } else {
        this.addCateFormData.cat_level = 0;
        this.addCateFormData.cat_pid = 0;
      }
      // console.log(val, this.selectedKeys);
    },

    // 添加分类对话框关闭
    addCateDialogClosed() {
      this.$refs.addCateForm.resetFields();

      this.addCateFormData.cat_level = 0;
      this.addCateFormData.cat_pid = 0;
      this.selectedKeys = [];
    },

    // 确定添加分类
    saveAddCate() {
      this.$refs.addCateForm.validate(async (valid) => {
        if (!valid) return;

        let { data: res } = await this.$http.post(
          "/categories",
          this.addCateFormData
        );
        if (res.meta.status != 201) return this.$message.error("添加分类失败");

        this.$message.success("添加分类成功");
        this.getCategory();
      });
      this.addCateDialogVisible = false;
    },

    // 修改分类信息
    async editCateInfo(payload) {
      this.editCateInfoForm.cate_name = payload.cat_name;
      this.curEditId = payload.cat_id;
      this.editDialogVisible = true;
    },

    // 保存修改分类信息
    async savaEditCateInfo() {
      let { data: res } = await this.$http.put(
        `/categories/${this.curEditId}`,
        {
          cat_name: this.editCateInfoForm.cate_name,
        }
      );
      if (res.meta.status != 200)
        return this.$message.error("修改分类信息失败");
      this.$message.success("修改分类信息成功");
      // 重新获取分类列表数据
      this.getCategory();
      this.editDialogVisible = false;
    },

    // 删除某个分类
    async deleteCate(payload) {
      this.$confirm("此操作将永久删除该分类, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let {data:res} = await this.$http.delete(`categories/${payload.cat_id}`);
          if(res.meta.status != 200)return this.$message.error("已取消删除");
          this.$message({
            type: "success",
            message: "删除分类成功!",
          });
          // 重新获取分类数据
          this.getCategory();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 添加分类操作
    async addCateOperation() {
      let { data: res } = await this.$http("/categories", {
        params: { type: 2 },
      });

      if (res.meta.status != 200)
        return this.$message.error("获取父类分类数据失败");
      this.$message.success("获取父级分类数据成功");
      this.categoriesTo2LevelData = res.data;
      console.log(this.categoriesTo2LevelData, this.categoriesData);
      this.addCateDialogVisible = true;
    },
  },
};
</script>

<style scoped>
.cascader-select {
  width: 100%;
}
</style>